import { contextBridge, ipcRenderer } from 'electron'
import { electronAPI } from '@electron-toolkit/preload'
import { lrcToNetease } from '../main/utils/lrcToNetease'
// Custom APIs for renderer
const api = {}
enum Prefix {
  music = 'music',
  file = 'file',
  sys = 'sys'
}
const electronApi = {
  ...electronAPI,
  getTitle: () => ipcRenderer.invoke(`${Prefix.sys}:getTitle`),
  getMusicInfo: (audioPath: string | Buffer) =>
    ipcRenderer.invoke(`${Prefix.file}:getMusicInfo`, audioPath),
  // 选择音乐文件夹
  selectMusicFolder: () => ipcRenderer.invoke(`music:select-music-folder`),
  // 获取缓存数据
  getMusicListCache: () => ipcRenderer.invoke(`${Prefix.music}:get-musicList-cache`),
  // 播放音乐
  searchMusic: (id: string) => ipcRenderer.invoke(`${Prefix.music}:search-music`, id),
  // 解析lrc歌词,转换成网易云歌词格式
  lrcToNetease
}

// Use `contextBridge` APIs to expose Electron APIs to
// renderer only if context isolation is enabled, otherwise
// just add to the DOM global.
if (process.contextIsolated) {
  try {
    contextBridge.exposeInMainWorld('electron', electronApi)
    contextBridge.exposeInMainWorld('api', api)
  } catch (error) {
    console.error(error)
  }
} else {
  // @ts-ignore (define in dts)
  window.electron = electronAPI
  // @ts-ignore (define in dts)
  window.api = api
}
